package org.acghub.mtdb.core;

import java.util.concurrent.Executor;

/**
 * @author zhouhe
 */
final class LogTask implements Log {

    private final Runnable commitRunnable;
    private final Executor commitExecutor;
    private final Runnable rollbackRunnable;
    private final Executor rollbackExecutor;

    private LogTask(Runnable commitRunnable, Executor commitExecutor, Runnable rollbackRunnable, Executor rollbackExecutor) {
        this.commitRunnable = commitRunnable;
        this.commitExecutor = commitExecutor;
        this.rollbackRunnable = rollbackRunnable;
        this.rollbackExecutor = rollbackExecutor;
    }


    @Override
    public void commit() {
        execute(commitRunnable, commitExecutor);
    }

    @Override
    public void rollback() {
        execute(rollbackRunnable, rollbackExecutor);
    }

    private void execute(Runnable r, Executor executor) {
        if (r == null) {
            return;
        }
        if (executor != null) {
            executor.execute(r);
        } else {
            r.run();
        }
    }

    static LogTask commit(Runnable r) {
        return commit(r, null);
    }

    static LogTask commit(Runnable r, Executor executor) {
        return new LogTask(r, executor, null, null);
    }

    static LogTask rollback(Runnable r) {
        return rollback(r, null);
    }

    static LogTask rollback(Runnable r, Executor executor) {
        return new LogTask(null, null, r, executor);
    }

    static LogTask any(Runnable r) {
        return any(r, null);
    }

    static LogTask any(Runnable r, Executor executor) {
        return new LogTask(r, executor, r, executor);
    }
}
